package com.atguigu.cart.interceptor;

import com.atguigu.cart.to.UserInfoTo;
import com.atguigu.common.vo.MemberResponseVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.UUID;

import static com.atguigu.common.constants.SessionAttrKeyConstant.LOGIN_USER;
import static com.atguigu.common.constants.CartConstant.TEMP_USER_COOKIE_NAME;
import static com.atguigu.common.constants.CartConstant.TEMP_USER_COOKIE_TIMEOUT;

/**
 * description: CartInterceptor
 * date: 2022/12/15 19:48
 * author: MR.孙
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /** 目标方法执行之前
     * 拦截器逻辑：业务执行之前，判断是否登录，若登录则封装用户信息，将标识位设置为true，
     * postHandler就不再设置作用域和有效时间，否则为其创建一个user-key
     * 注意细节：整合SpringSession之后，Session获取数据都是从Redis中获取的
     * 使用ThreadLocal，解决线程共享数据问题，方便同一线程共享UserInfoTo
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();

        MemberResponseVo memberResponseVo = (MemberResponseVo) session.getAttribute(LOGIN_USER);
        //判断用户是否登录成功
        if (memberResponseVo!=null) {
            //成功，封装用户信息
            userInfoTo.setUserId(memberResponseVo.getId());
        }

        //获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                //如果有user-key则封装用户信息
                if (cookieName.equals(TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    //有cookie了设置标志位为true
                    userInfoTo.setTempUser(true);
                }
            }
        }

        //如果没有临时用户就生成一个
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后，分配临时用户来浏览器保存
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler handler  that started asynchronous
     * execution, for type and/or instance examination
     * @param modelAndView the {@code ModelAndView} that the handler returned
     * (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();

        //如果没有临时用户才需要创建cookie
        if (!userInfoTo.getTempUser()) {
            Cookie cookie = new Cookie(TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            //设置作用域
            cookie.setDomain("gulimall.com");
            //设置过期时间,单位为second
            cookie.setMaxAge(TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }


    }
}
